package com.classroom.smart.controller;

import com.classroom.smart.constant.MessageConstant;
import com.classroom.smart.constant.RedisMessageConstant;
import com.classroom.smart.result.Result;
import com.classroom.smart.utils.SMSUtils;
import com.classroom.smart.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired(required = true)
    private JedisPool jedisPool;

    //预约时发送的短信，为了校验手机号是否正确
    @PostMapping("sendByOrder")
    public Result sendByOrder(String telephone){
        //获取4位数字的验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //调用SMSUtils发送短信  第一个参数：短信模板CODE  第二个参数：手机号  第三个参数：验证码
            SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE , telephone , code+"");
            //在Redis中存储一份有效期为5分钟的短信验证码
            jedis.setex(telephone+"_"+ RedisMessageConstant.SENDTYPE_ORDER , 5*60 , code+"");
            return new Result(true , MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false , MessageConstant.SEND_VALIDATECODE_FAIL);
        } finally {
            if(jedis!=null){
                //自动将jedis连接，归还至连接池中
                jedis.close();
            }
        }
    }

}
